# 壁球小游戏与键盘的基本使用
# 导入必要的库
import sys
import os
import pygame

# 初始化pygame
pygame.init()

# 声明各种变量
size = width, height = 600, 400
fps = 100
speed = [1, 1]
WHITE = (255, 255, 255)
BASE_DIR = os.path.realpath(os.path.dirname(sys.argv[0]))
BALL_DIR = os.path.join(BASE_DIR, 'ball.gif')

# 初始化窗口
screen = pygame.display.set_mode(size)
pygame.display.set_caption('ball')

# 加载图片Surface对象
ball = pygame.image.load(BALL_DIR)
ball_rect = ball.get_rect()

# 创建时间对象
fclock = pygame.time.Clock()

# 编写游戏循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed[0] = speed[0] - 1
            elif event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1
            elif event.key == pygame.K_UP:
                speed[1] = speed[1] - 1
            elif event.key == pygame.K_DOWN:
                speed[1] = speed[1] + 1
            elif event.key == pygame.K_SPACE:
                speed[0] = 1
                speed[1] = 1

    ball_rect = ball_rect.move(speed[0], speed[1])

    if ball_rect.left < 0 or ball_rect.right > width:
        speed[0] = -speed[0]
    if ball_rect.top < 0 or ball_rect.bottom > height:
        speed[1] = -speed[1]

    # 窗口刷新，窗口填充，对象绑定，时间设置
    screen.fill(WHITE)
    screen.blit(ball, ball_rect)
    fclock.tick(fps)
    pygame.display.update()
